package com.zhenyi.xiaohuoche.admin.web;

import java.io.File;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.utils.DateUtils;
import com.utils.PathUtils;
import com.utils.interceptor.TestInterceptor;
import com.xhc.common.model.XhcOrder;
import com.xhc.common.model.XhcTicket;
import com.xhc.common.model.XhcUserTicket;
import com.xhc.common.model.XhcWechat;
import com.zhenyi.xhc.core.OrderUtils;
import com.zhenyi.xhc.core.TicketUtils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

public class TicketController extends XHCAdminController {

	@Clear
	@Before(TestInterceptor.class)
	public void updateqrcode() {
		Long userTicketId = getParaToLong("userTicketId");
		if (userTicketId == null) {
			renderFailure("userTicketId");
			return;
		}
		XhcUserTicket userTicket = XhcUserTicket.dao.findById(userTicketId);
		if (userTicket == null) {
			renderFailure("userTicket");
			return;
		}
		if (userTicket.getOrderId() == null) {
			renderFailure("userTicket.getOrderId(");
			return;
		}
		String code = piaoHashids.encode(userTicketId);
		String no = OrderUtils.gen(userTicket.getId());
		String qrcodeUrl = TicketUtils.qrcodeImage(code, no, userTicket.getTitle(), "时间: " + userTicket.getTime());
		userTicket.setQrcode(qrcodeUrl);
		userTicket.update();
		renderSuccess(qrcodeUrl);
	}

	/**
	 * 按照年月日下载进场统计
	 */
	public void downloadEnroll() {
		Date start = getStartDate();
		Date end = getEndDate();
		String type = "进场统计";
		String title = type + DateUtil.now();
		SqlPara sqlPara = xhcDb.getSqlPara("Endroll", start, end);
		List<Record> pages = xhcDb.find(sqlPara);
		String excelTitle = DateUtils.dateFormat(start, DateUtils.YYYYMMDD) + "至"
				+ DateUtils.dateFormat(end, DateUtils.YYYYMMDD) + type;
		ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
		for (Record record : pages) {
			Map<String, Object> item = new LinkedHashMap<>();
			item.put("微信昵称", record.get("nickName"));
			item.put("进场时间", record.getDate("addTime"));
			item.put("票面时间", record.getDate("ticketTime"));
			rows.add(item);
		}

		String path = PathUtils.getFile("xhc", "download", title + ".xlsx");
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.merge(2, excelTitle);
		// 一次性写出内容
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	@Clear
	public void active() {
		String code = getPara("code");
		if (StrKit.isBlank(code)) {
			renderMsg("票号为空");
			return;
		}
		Cache cache = Redis.use();
		// String codeValue = "";
		// try {
		// codeValue = cache.get(code);
		// } catch (Exception e) {
		// }
		// if (StrKit.notBlank(codeValue)) {
		// renderMsg("已激活");
		// return;
		// }
		if (XhcUserTicket.dao.searchFirst("qrcode", code) != null) {
			renderMsg("已激活");
			return;
		}
		int min = DateUtil.thisMinute();
		int hour = DateUtil.thisHour(true);
		if (min > 30) {
			hour += 1;
		}
		String activeTime = DateUtil.today() + " " + hour + ":00:00";

		SqlPara sqlPara = db.getSqlPara("XHCFindTicketByTime", Kv.by("time", activeTime));
		XhcTicket ticket = XhcTicket.dao.findFirst(sqlPara);
		if (ticket == null) {
			renderMsg("添加失败");
		}
		XhcUserTicket userTicket = new XhcUserTicket();
		userTicket.setTicketId(ticket.getId());
		userTicket.setTime(ticket.getTime());
		userTicket.setStatus(1);
		userTicket.setPaid(new BigDecimal(0));
		userTicket.setType(1);
		userTicket.setQrcode(code);
		userTicket.setName("现场购票");
		userTicket.save();

		ticket.updateTicketCount();
		// System.out.println(activeTime);
		String key = code;
		cache.setex(key, 7200, userTicket.getId());
		renderSuccess(ticket);
		renderMsg("添加成功 " + activeTime);
	}

	public void updateTicketInfo() {
		Long ticketId = getParaToLong("ticketId");
		XhcTicket ticket = XhcTicket.dao.findById(ticketId);
		ticket.updateTicketCount();
		renderSuccess();
	}

	@Override
	public void list() {
		Date startDate = getStartDate();// getPara("startDate");
		Date endDate = getEndDate();// getPara("endDate");
		SqlPara sqlPara = xhcDb.getSqlPara("TicketList", startDate, endDate);
		Page<XhcTicket> pages = XhcTicket.dao.paginate(getPage(), getPageSize(), sqlPara);
		List<XhcTicket> items = pages.getList();
		for (XhcTicket xhcTicket : items) {
			xhcTicket.setDefaultInfo();
		}
		setItems(JsonKit.toJson(items));
		setRainbow(pages);
		// renderJson(items);
		render("/xhc/admin/ticket/list.html");
	}

	public void edit() {
		setAttr("today", DateUtil.today());
		render("/xhc/admin/ticket/edit.html");
	}

	/**
	 * 票务时间是否在选中时间范围内
	 * 
	 * @param item
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	private Boolean timeOfRange(XhcTicket item, String startTimeStr, String endTimeStr) {
		SimpleDateFormat dateFm = new SimpleDateFormat("HH");
		String hoursStr = dateFm.format(item.getTime());
		int hours = Integer.parseInt(hoursStr);
		String startTimeFmt = startTimeStr.split(":")[0];
		String endTimeStrFmt = endTimeStr.split(":")[0];
		int startTime = Integer.parseInt(startTimeFmt);
		int endTime = Integer.parseInt(endTimeStrFmt);
		Boolean flag = false;
		if (hours >= startTime && hours <= endTime) {
			flag = true;
		}
		return flag;
	}

	@Override
	public void submit() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		String week = getPara("week", "1;2;3;4;5;6;7");
		String title1 = getPara("title1", null);
		String title2 = getPara("title2", null);
		String title3 = getPara("title3", null);
		String title4 = getPara("title4", null);
		String title5 = getPara("title5", null);
		String discount = getPara("discount", "");

		BigDecimal price1 = new BigDecimal(getPara("price1", "0"));
		BigDecimal price2 = new BigDecimal(getPara("price2", "0"));
		BigDecimal price3 = new BigDecimal(getPara("price3", "0"));
		BigDecimal price4 = new BigDecimal(getPara("price4", "0"));
		BigDecimal price5 = new BigDecimal(getPara("price5", "0"));
		String tips = getPara("tips", "");
		Integer disable = getParaToInt("disable", 1);
		Integer limit = getParaToInt("limit", null);
		Integer[] weekCount = { 0, 0, 0, 0, 0, 0, 0 };
		String[] weekArr = week.split(";");
		for (String weekStr : weekArr) {
			int weekInt = Integer.parseInt(weekStr);
			weekCount[weekInt - 1] = 1;
		}
		if (StrKit.isBlank(startDate) && StrKit.isBlank(endDate)) {
			renderMsg("日期范围不能为空");
			return;
		}
		if (StrKit.isBlank(startTime) && StrKit.isBlank(endTime)) {
			renderMsg("时间范围不能为空");
			return;
		}
		SqlPara sqlPara = xhcDb.getSqlPara("FindRangeTickes", startDate, endDate);
		List<XhcTicket> items = XhcTicket.dao.find(sqlPara);
		int size = items.size();
		if (size == 0) {
			renderMsg("没有票");
			return;
		}
		ArrayList<XhcTicket> temp = new ArrayList<>();

		for (XhcTicket item : items) {
			Integer day = item.getTime().getDay();
			day = (day + 6) % 7;
			if (timeOfRange(item, startTime, endTime) && weekCount[day] == 1) {
				temp.add(item);
			}
		}
		size = temp.size();
		if (size == 0) {
			renderMsg("没有票");
			return;
		}

		Boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				for (XhcTicket item : temp) {
					item.setTitle1(title1);
					item.setTitle2(title2);
					item.setTitle3(title3);
					item.setTitle4(title4);
					item.setTitle5(title5);
					item.setPrice1(price1);
					item.setPrice2(price2);
					item.setPrice3(price3);
					item.setPrice4(price4);
					item.setPrice5(price5);
					item.setDiscount(discount);
					item.setTips(tips);
					item.setDisable(disable);
					item.setLimit(limit);
					if (!item.update()) {
						return false;
					}
				}
				return true;
			}
		});
		renderFlag(flag);
	}

	@Override
	public void info() {
		String notification = new FileReader(PathUtils.getFile("data", "xhc", "notification.txt")).readString();
		String businessTime = new FileReader(PathUtils.getFile("data", "xhc", "businessTime.txt")).readString();
		setAttr("notification", notification);
		setAttr("businessTime", businessTime);
		render("/xhc/admin/ticket/info.html");
	}

	public void submitInfo() {
		String notification = getPara("notification", "");
		String businessTime = getPara("businessTime", "");
		new FileWriter(PathUtils.getFile("data", "xhc", "businessTime.txt")).write(businessTime);
		new FileWriter(PathUtils.getFile("data", "xhc", "notification.txt")).write(notification);
		renderSuccess();
	}

	@Before(TestInterceptor.class)
	public void fakePay() {
		String mobile = "136";
		String openId = "oAngF0VdBpU29x7T8-CVP68QCXIw";

		Integer price1Count = getParaToInt("price1Count", 1);
		Integer price2Count = getParaToInt("price2Count", 0);
		Integer price3Count = getParaToInt("price3Count", 0);
		Integer price4Count = getParaToInt("price4Count", 0);
		Integer price5Count = getParaToInt("price5Count", 0);

		Long ticketId = getParaToLong("ticketId");
		if (ticketId == null) {
			renderFailure("ticket id error");
			return;
		}

		String name = getPara("name", "未填写");
		if (StrKit.isBlank(openId)) {
			renderFailure("openId null");
			return;
		}

		XhcTicket ticket = XhcTicket.dao.findById(ticketId);
		BigDecimal totalPrice = new BigDecimal(0);
		totalPrice = totalPrice.add(ticket.getPrice1().multiply(new BigDecimal(price1Count)));
		totalPrice = totalPrice.add(ticket.getPrice2().multiply(new BigDecimal(price2Count)));
		totalPrice = totalPrice.add(ticket.getPrice3().multiply(new BigDecimal(price3Count)));
		totalPrice = totalPrice.add(ticket.getPrice4().multiply(new BigDecimal(price4Count)));
		totalPrice = totalPrice.add(ticket.getPrice5().multiply(new BigDecimal(price5Count)));
		totalPrice = totalPrice.multiply(new BigDecimal(100));
		String total = totalPrice.intValue() + "";
		if ("0".equals(total)) {
			renderMsg("购买金额不能为0");
			return;
		}
		Date time = ticket.getTime();
		XhcOrder order = new XhcOrder();
		order.setAddTime();
		String ip = IpKit.getRealIpV2(getRequest());
		order.setStatus(0);
		order.setPaidIp(ip);
		// order.setCardId(cardId);
		order.setOpenid(openId);
		order.setAddTime();
		order.setTotalFee(total);
		order.setPrice(Integer.parseInt(total));
		order.setAppId(APP_ID);
		order.setMchId(PARTNER);
		order.setRaw(JsonKit.toJson(ticket));
		order.setName(name);
		order.setMobile(mobile);
		// order.setatta
		order.setAttach("ticket");
		order.save();
		order.setOutTradeNo(hashids.encode(order.getId()));
		// order.setNo(hashids.encode(order.getId()));
		Long orderId = order.getId();
		XhcWechat wechat = XhcWechat.dao.findByOpenId(openId);
		Long wechatId = wechat.getId();
		for (int count = 0; count < price1Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 1, name, mobile);
		}
		for (int count = 0; count < price2Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 2, name, mobile);
		}
		for (int count = 0; count < price3Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 3, name, mobile);
		}
		for (int count = 0; count < price4Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 4, name, mobile);
		}
		for (int count = 0; count < price5Count; count++) {
			saveTicket(ticket, orderId, wechatId, time, 5, name, mobile);
		}
		// String prepayId = renderPay(order.getOutTradeNo(), "小火车", total,
		// openId, order.getAttach());
		String prepayId = "prepayId";
		order.setPrepayId(prepayId);
		order.update();
		// renderSuccess();
		renderMsg("测试购买");
	}

	private boolean saveTicket(XhcTicket ticket, Long orderId, Long wechatId, Date time, int type, String name,
			String mobile) {
		Long ticketId = ticket.getId();
		ticket.print();
		XhcUserTicket userTicket = new XhcUserTicket();
		userTicket.setTicketId(ticketId);
		userTicket.setOrderId(orderId);
		userTicket.setWechatId(wechatId);
		userTicket.setTime(time);
		userTicket.setAddTime();
		userTicket.setStatus(0);
		userTicket.setName(name);
		userTicket.setMobile(mobile);
		userTicket.setType(type);
		userTicket.setTitle(ticket.getStr("title" + type));
		BigDecimal paid = ticket.getTicketPrice(type);
		paid = paid.multiply(new BigDecimal(100));
		userTicket.setPaid(paid);
		userTicket.save();
		Long id = userTicket.getId();
		String code = piaoHashids.encode(id);
		String url = QRCODE_VERIFY + code;
		genQRCode(code, url);
		String qrcode = QRCODE_HOST + code + ".png";
		userTicket.setQrcode(qrcode);
		return userTicket.update();
	}

}
